<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="mini" inline>
      <el-form-item prop="progressChkType">
        <el-select v-model="queryParams.progressChkType" placeholder="检查类型" style="width: 120px;" clearable>
          <el-option v-for="dict in dict.type.cq_progress_chk_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="deptId1">
        <treeselect
          v-model="queryParams.deptId1"
          class="tree-select-custom"
          :options="deptOptions"
          no-results-text="暂无数据匹配"
          no-options-text="暂无数据"
          :normalizer="normalizerDept"
          @select="getProjectList"
          placeholder="请选择所属部门"
        />
      </el-form-item>
      <el-form-item prop="projectName">
        <el-input v-model.trim="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" style="width: 160px" />
      </el-form-item>
      <el-form-item prop="randomType" v-if="hasRandomType">
        <el-select v-model="queryParams.randomType" placeholder="检查单位" clearable style="width: 100px">
          <el-option v-for="dict in dict.type.cq_random_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="锁定状态" clearable style="width: 100px">
          <el-option v-for="dict in lockStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="检查开始日期"
          end-placeholder="检查结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['cq:civil:add']" v-show="processType === 'civil'">新增</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['cq:handcover:add']" v-show="processType === 'handcover'">新增</el-button>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="handleExport" v-if="showBtns.isExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="small" :data="constructionList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="检查类型" align="center" min-width="80" key="progressChkType">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_progress_chk_type" :value="row.progressChkType" />
      </el-table-column>
      <el-table-column label="所属部门" prop="showDeptName" show-overflow-tooltip min-width="200" key="showDeptName" />
      <el-table-column label="项目" prop="projectName" :show-overflow-tooltip="true" width="150" key="projectName" />
      <el-table-column label="检查标段" prop="section" show-overflow-tooltip width="80" key="section" />
      <el-table-column label="项目(检查口径)" prop="inpectionCaliber" show-overflow-tooltip width="110" key="inpectionCaliber" />
      <el-table-column label="施工单位" prop="constructionName" show-overflow-tooltip min-width="200" key="constructionName" />
      <el-table-column label="检查单位" align="center" min-width="80" key="randomType">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_random_type" :value="row.randomType" />
      </el-table-column>

      <el-table-column v-for="item in scoreTypeList" :key="item.value" :label="item.label" align="center" min-width="100">
        <template slot-scope="{ row }">
          <el-popover placement="top" trigger="hover" v-if="item.children">
            <div class="material-tab">
              <div class="material-item item-special" v-for="sub in item.children" :key="sub.value" :class="row[sub.key + 'Score'] | scoreClass(sub.key)">
                <div v-if="!sub.children" class="item-cursor" @click="leakage(row, sub.value)">
                  <div>{{ sub.label }}</div>
                  <div>{{ row | scoreName(sub.key) }}</div>
                </div>
                <div v-else class="material-item-type">
                  <div>
                    <div>{{ sub.label }}</div>
                    <div>{{ row | scoreName(sub.key) }}</div>
                  </div>
                  <div class="type-line" />
                  <div class="gc-bs">
                    <div v-for="type in sub.children" :key="'yt'+type.value" class="label-value" @click="leakage(row, sub.value, type)">
                      <span>{{ type.label }}</span>
                      <span> {{ row[type.scoreKey] || '/' }} </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div slot="reference" class="material-item item-cursor" :class="row[item.key + 'Level'] | scoreClass(item.key)">{{ row | scoreName(item.key, 'level1') }}</div>
          </el-popover>
          <div v-else class="material-item item-cursor" :class="row[item.key + 'Level'] | scoreClass(item.key)" @click="leakage(row, item.value)">{{ row | scoreName(item.key, 'level1') }}</div>
        </template>
      </el-table-column>

      <el-table-column label="检查人员" align="center" show-overflow-tooltip min-width="100" prop="principalUserName" />
      <el-table-column label="检查时间" align="center" prop="checkDate" width="100" />
      <el-table-column label="锁定状态" align="center" width="70" fixed="right">
        <div slot-scope="{ row }">
          <div @click="toggleIsEnable(row)" style="display: inline-block; cursor: pointer" v-if="row.isEditEnable">
            <i class="el-icon-loading" v-if="!!row.isEnableLoading" />
            <el-switch class="g-switch-in" v-model="row.isEnable" :active-value="1" :inactive-value="0" active-text="锁定" inactive-text="未锁" :width="50" style="pointer-events: none" v-else />
          </div>
          <el-tag size="small" :type="row.isEnable ? 'primary' : 'info'" v-else>{{ row.isEnable ? '锁定' : '未锁' }}</el-tag>
        </div>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right" class-name="small-padding">
        <template slot-scope="{ row }">
          <div v-if="row.showBtns">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)" v-if="row.showBtns.edit && !row.isEnable">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)" v-if="row.showBtns.remove && !row.isEnable">删除</el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleRecheck(row)" v-if="row.showBtns.recheck && row.isEnable && row.isRecheck">{{ row.chkStep === chkStep.NEEDRECHK ? '复查' : '重新检查' }}</el-button>
            <el-button size="mini" type="text" icon="el-icon-tickets" @click="handleDetail(row)" v-if="row.showBtns.itemInfo">详情</el-button>
            <el-button icon="el-icon-download" type="text" :loading="row.exportLoading" @click="handleTaskExport(row)" v-if="showBtns.isExport && row.isEnable">导出</el-button>
            <el-button size="mini" type="text" icon="el-icon-view" :disabled="previewDisabled(row)" @click="handleReportPreview(row)" v-if="row.showBtns.preview && row.randomType === 'DEPT1'">预览</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.forceRemoveLoading" @click="handleForceRemove(row)" v-if="row.showBtns.forceRemove && !row.isEnable">强制删除</el-button>
          </div>
          <!--
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="handleDetail(row)" v-if="row.showBtns.itemInfo">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleReportPreview(row)" :disabled="previewDisabled(row)" v-if="row.showBtns.preview && row.randomType === 'DEPT1'">预览</el-button>
          <el-dropdown>
            <el-button size="mini" type="text" icon="el-icon-more" style="margin-left: 10px">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-edit" @click.native="handleUpdate(row)" v-if="row.showBtns.edit && !row.isEnable">修改</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="handleDelete(row)" v-if="row.showBtns.remove && !row.isEnable" style="color: #f56c6c">删除</el-dropdown-item>
              <el-dropdown-item icon="el-icon-edit" @click.native="$refs.OutsideQuesList.open(row)">测区外问题</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--新增与修改土建过程-->
    <add-update ref="addUpdateRef" :process-type="processType" @close="getList" />
    <!--防渗漏-->
    <antiseep ref="antiseepRef" :process-type="processType" @submitSuccess="submitSuccess" />
    <!-- 详情 -->
    <construction-detail ref="constructionDetailRef" />
    <jz-report-preview v-if="processType === 'handcover'" ref="handcoverReportPreviewRef" />
    <tj-report-preview v-if="processType === 'civil'" ref="civilReportPreviewRef" />
    <OutsideQuesList ref="OutsideQuesList" />
  </div>
</template>

<script>
import auth from '@/plugins/auth'
import { inspectTypeListWithKey, getScoreTypeEnum, lockStatusList, chkStep } from '@/utils/baseData'
import {
  cqRdcScorePage,
  cqRdcScoreRemove,
  cqRdcScoreForceRemove,
  cqRdcScoreEnableTask,
  cqRdcScoreDisableTask,
  cqRdcScoreExportReport,
  getProcessWordRecord
} from '@/api/projectInspection/courseCheck'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Antiseep from './components/antiseep'
import ConstructionDetail from './components/constructionDetail'
import addUpdate from './components/addUpdate'
import TjReportPreview from './components/TjReportPreview'
import JzReportPreview from './components/JzReportPreview'
import OutsideQuesList from './components/OutsideQuesList'

// 移除 '管理动作'; '空鼓开裂'字段有差异，改为 zlKg
const inspectTypeList = JSON.parse(JSON.stringify(inspectTypeListWithKey))
inspectTypeList.map(item =>
  item.scoreTypeList.map((i, index) => {
    if (i.key === 'gldz') item.scoreTypeList.splice(index, 1)
    if (i.children) i.children.map(j => j.key === 'zlKgkl' && (j.key = 'zlKg'))
  })
)

export default {
  name: 'ConstructionCourse',
  components: {
    Treeselect,
    Antiseep,
    ConstructionDetail,
    addUpdate,
    TjReportPreview,
    JzReportPreview,
    OutsideQuesList
  },
  dicts: ['cq_random_type', 'cq_process_type', 'cq_progress_chk_type'],
  filters: {
    scoreClass(val, scoreType) {
      if (!val) return ''
      if (scoreType === 'fsl') {
        if (val === 'A') return 'blue'
        if (val === 'B' || val === 'C') return 'red'
        return ''
      }
      if (val === 'A' || val >= 90) return 'green'
      if (val === 'B' || (val < 90 && val >= 80)) return 'blue'
      if (val === 'C' || val < 80) return 'red'
      return ''
    },
    scoreName(item = {}, key, isLevel1) {
      // 一级大类才显示等级
      const level = isLevel1 ? item[`${key}Level`] || '' : ''
      const score = item[`${key}Score`] || ''
      const val = level ? `${level}${score ? `(${score})` : ''}` : score
      return val || '/'
    }
  },
  data() {
    return {
      lockStatusList,
      antiseepShow: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 土建表格数据
      constructionList: [],
      // 日期范围
      dateRange: [],
      // 专业类别
      specialTypes: [],
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        progressChkType: '',
        deptId1: undefined,
        projectName: undefined,
        randomType: '',
        isEnable: '',
        processType: undefined,
        startTime: '',
        endTime: ''
      },
      hasRandomType: false,
      exportLoading: false,
      processType: '', // 检查过程类型
      specialTypeName: '', // 专业类别名称
      chkStep: chkStep
    }
  },
  computed: {
    scoreTypeList() {
      const { processType } = this
      if (!processType) return []
      const item = inspectTypeList.find(i => i.processType === processType)
      return item?.scoreTypeList || []
    },
    showBtns() {
      // 操作按钮权限
      const { processType } = this
      const edit = auth.hasPermi(`cq:${processType}:edit`)
      const remove = auth.hasPermi(`cq:${processType}:remove`)
      const itemInfo = auth.hasPermi(`cq:${processType}:itemInfo`)
      const preview = auth.hasPermi(`cq:${processType}:preview`)
      // 有权解锁(启用)
      const enable = auth.hasPermi(`cq:${processType}:enable`)
      // 有权锁定(禁用)
      const disable = auth.hasPermi(`cq:${processType}:disable`)
      const isExport = auth.hasPermi(`cq:${processType}:export`)
      // 复查
      const recheck = auth.hasPermi(`cq:${processType}:recheck`)
      const forceRemove = auth.hasPermi(`cq:${processType}:forceRemove`)
      return { edit, remove, itemInfo, preview, enable, disable, isExport, recheck, forceRemove }
    }
  },
  created() {
    this.getSpecialList()
    this.getDeptTree()
  },
  methods: {
    // 判断 检查单位 权限
    getRandoTypePermission() {
      const hasDept1 = auth.hasPermi(`${this.processType}:DEPT1`) // 有集团 权限
      const hasDept2 = auth.hasPermi(`${this.processType}:DEPT2`) // 有集群 权限
      if (hasDept1 && hasDept2) {
        this.queryParams.randomType = ''
        this.hasRandomType = true
      } else {
        this.hasRandomType = false
        if (hasDept1) {
          this.queryParams.randomType = 'DEPT1'
        } else if (hasDept2) {
          this.queryParams.randomType = 'DEPT2'
        } else {
          this.queryParams.randomType = 'NoList'
        }
      }
    },
    handleDetail(row) {
      this.$refs.constructionDetailRef.init(row)
    },
    previewDisabled(data) {
      const flag = data.zlScore || data.aqScore || data.wmScore || data.aqwmScore
      return !flag
    },
    /**
     * 处理报表预览点击
     * @param row
     */
    handleReportPreview(row) {
      this.$refs[this.processType + 'ReportPreviewRef'].init(row)
    },
    submitSuccess() {
      this.getList()
    },
    /** 查询专业类别列表 */
    getSpecialList() {
      this.getDicts('cq_process_type').then(response => {
        this.specialTypes = response.data
        const path = this.$route.path
        this.specialTypeName = path.includes('ConstructionCourse') ? '土建' : '精装'
        const constructionSpecialType = this.specialTypes.find(item => item.dictLabel.includes(this.specialTypeName))
        this.processType = constructionSpecialType && constructionSpecialType.dictValue
        this.queryParams.processType = this.processType
        this.getRandoTypePermission()
        this.getList()
      })
        .catch(() => (this.loading = false))
    },
    // 防渗漏
    leakage(row, scoreType, ytType) {
      const { processType } = this
      const { isEnable } = row
      // 锁定状态不可点击
      if (isEnable) return this.$message.info('已被锁定，无法操作')

      const processName = this.dict?.label.cq_process_type[processType] || ''
      const scoreType2label = getScoreTypeEnum(processType) || {}
      const scoreName = scoreType2label[scoreType] || ''
      const title = `${processName}${scoreName ? `-${scoreName}` : ''}`
      const params = { scoreType, title }
      if (ytType) {
        params.title = `${params.title}-${ytType.label}`
        params.productType = ytType.value
      }
      this.$refs.antiseepRef.show = true
      this.$refs.antiseepRef.init(row, params)
    },
    /** 查询土建列表 */
    async getList() {
      const { showBtns } = this
      const opt = this.getQuery()
      if (!opt) return

      this.loading = true
      const res = await cqRdcScorePage(opt).catch(() => false)
      this.loading = false
      if (res === false) return

      const data = res.rows || []
      const deptName = i => [i.deptName1, i.deptName2, i.deptName3].filter(i => i).join(' - ')
      data.map(i => {
        i.showDeptName = deptName(i)
        i.isEnableLoading = false
        i.isEditEnable = i.isEnable ? showBtns.enable : showBtns.disable
        i.showBtns = showBtns
        i.isRecheck = false // 是否 需要复查
        i.exportLoading = false // 任务下载状态
        i.forceRemoveLoading = false

        for (let j = 0; j < this.scoreTypeList.length; j++) {
          const scoreClassVal = this.$options.filters['scoreClass'](i[this.scoreTypeList[j].key + 'Level'], this.scoreTypeList[j].key)
          if (scoreClassVal === 'red' && i.chkStep === 'NEEDRECHK' || i.chkStep === 'NEEDDOUCHK') {
            i.isRecheck = true
          }
        }
      })

      this.constructionList = data
      this.total = res.total || 0
    },
    getQuery() {
      const { dateRange } = this
      const opt = { ...this.queryParams }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        opt.startTime = dateRange[0]
        opt.endTime = dateRange[1]
      } else {
        opt.startTime = ''
        opt.endTime = ''
      }
      return opt
    },
    /**
       * 查询部门与项目下拉树结构
       */
    getDeptTree() {
      treeselect({}).then((response) => {
        this.deptOptions = response.data
      })
    },
    getProjectList(node) {
      this.queryParams.projectName = ''
    },
    /** 转换检索部门数据结构 */
    normalizerDept(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.fid,
        label: node.label,
        children: node.children
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 复查
    handleRecheck(row) {
      const rowData = JSON.parse(JSON.stringify(row))
      this.$refs.addUpdateRef.handleRecheck(rowData)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addUpdateRef.handleAdd()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.addUpdateRef.handleUpdate(row)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`是否确认删除当前${this.specialTypeName}过程的数据项?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return cqRdcScoreRemove({ randomId: row.randomId, checkDate: row.checkDate })
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    // 强制删除
    async handleForceRemove(item) {
      const res1 = await this.$confirm(`确认强制删除当前${this.specialTypeName}过程的数据项?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { randomId: item.randomId, checkDate: item.checkDate }
      item.forceRemoveLoading = true
      const res = await cqRdcScoreForceRemove(opt).catch(() => false)
      item.forceRemoveLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.getList()
    },
    async handleExport() {
      if (!this.constructionList.length) return this.msgInfo('暂无数据')
      const opt = this.getQuery()
      if (!opt) return
      // 不传分页参数
      delete opt.pageNum
      delete opt.pageSize

      const filename = `${this.specialTypeName}过程检查表`
      const res1 = await this.$confirm(`确定导出${filename}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.exportLoading = true
      const res = await cqRdcScoreExportReport(opt).catch(() => false)
      this.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}_${new Date().Format('yyyyMMdd')}.xlsx`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    },
    async handleTaskExport(row) {
      const filename = `${row.projectName} - ${this.specialTypeName}过程（${this.dict.label.cq_random_type[row.randomType]}）检查整改联系单_${new Date().Format('yyyyMMdd')}.docx`
      const res1 = await this.$confirm(`确定导出《${filename}》?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return
      row.exportLoading = true
      const res = await getProcessWordRecord({taskId: row.randomId}).catch(() => false)
      row.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    },
    async toggleIsEnable(item) {
      if (item.isEnableLoading) return
      const isEnable = item.isEnable ? 0 : 1
      const name = isEnable === 1 ? '锁定' : '解锁'
      const res1 = await this.$confirm(`确认${name}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { taskId: item.randomId, isEnable }
      const submitApi = isEnable ? cqRdcScoreDisableTask : cqRdcScoreEnableTask
      item.isEnableLoading = true
      const res = await submitApi(opt).catch(() => false)
      item.isEnableLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
  $borderColor: #E4E7ED;
  .tree-select-custom {
    width: 300px;
    /deep/ {
      .vue-treeselect__control {
        height: 28px;
        font-size: 12px;
      }
      .vue-treeselect__placeholder,
      .vue-treeselect__single-value {
        line-height: 26px;
      }
      .vue-treeselect__input-container,
      .vue-treeselect__input {
        height: 26px;
      }
    }
  }
.material-tab {
  .material-item {
    padding: 6px 10px;
    margin: 0 10px;
  }
}
.material-item {
  display: inline-block;
  text-align: center;
  padding: 2px 10px;
  color: #909399;
  border: 1px currentColor dashed;
  border-radius: 4px;
  vertical-align: top;
}
  .item-cursor {
    cursor: pointer;
    &:hover {
      /*color: #409EFF;*/
    }
  }
.item-special {
  .material-item-type {
    display: flex;
    .type-line  {
      border-right: 1px currentColor dashed;
      margin: -6px 10px;
    }
    .gc-bs {
      cursor: pointer;
    }
    .label-value {
      text-align: left;
      span:nth-child(1) {
        margin-right: 10px;
      }
      &:hover {
        color: #409EFF;
      }
    }
  }
}
.green {
  color: #67c23a;
}
.blue {
  color: #409eff;
}
.red {
  color: #f56c6c;
}
</style>
